package ren.kane.phoenix.util.io;

import java.io.IOException;
import java.io.PipedInputStream;

/**
 * @author renrk(1275) on 2019-07-30 3:33 PM
 **/
public class Receiver extends Thread {
    // 管道输入流对象，它和“管道输出流(PipedOutputStream)”对象绑定，从而可以接收“管道输出流”的数据，再让用户读取
    private PipedInputStream pipedInputStream = new PipedInputStream();

    public PipedInputStream getPipedInputStream() {
        return pipedInputStream;
    }

    @Override
    public void run() {
        // readMessageOnce();
        readMessageContinued();
    }

    // 从“管道输入流”中读取1次数据
    private void readMessageOnce() {
        // 虽然buf的大小是2048个字节，但最多只会从“管道输入流”中读取1024个字节
        // 因为，“管道输入流”的缓冲区大小默认只有1024个字节
        byte[] buf = new byte[2048];
        try {
            int len = pipedInputStream.read(buf);
            System.out.println(new String(buf, 0, len));
            pipedInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 从“管道输入流”读取>1024个字节时，就停止读取
    private void readMessageContinued() {
        int total = 0;
        while (true) {
            byte[] buf = new byte[1024];
            try {
                int len = pipedInputStream.read(buf);
                total += len;
                System.out.println(new String(buf, 0, len));
                if (total > 1024) {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            pipedInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
